<template>
  <div class="p-2">
    <transition>
      <div class="search" v-show="showSearch">
        <el-form
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          label-width="68px"
        >
          <el-form-item label="用户名" prop="userName">
            <el-input
              v-model="queryParams.userName"
              placeholder="请输入用户名"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="手机号" prop="phoneNumber">
            <el-input
              v-model="queryParams.phoneNumber"
              placeholder="请输入手机号"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="登录状态" prop="status">
            <el-select
              v-model="queryParams.status"
              clearable
              placeholder="Select"
            >
              <el-option
                v-for="item in statusArr"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="登录时间" prop="age">
            <el-date-picker
              v-model="queryParams.timeRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">
              搜索
            </el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <!-- 按钮区 -->
    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb-1">
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete()"
              v-hasPermi="['system:user:remove']"
            >
              删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="Delete"
              :disabled="multiple"
              v-hasPermi="['system:user:import']"
            >
              导入
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="Delete"
              :disabled="multiple"
              v-hasPermi="['system:user:export']"
            >
              导出
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="DeleteFilled"
              @click="handleCleanAll"
              v-hasPermi="['system:user:export']"
            >
              清空
            </el-button>
          </el-col>
          <right-toolbar
            v-model:showSearch="showSearch"
            @queryTable="getLoginLogList"
          ></right-toolbar>
        </el-row>
      </template>

      <!-- 列表区 -->
      <el-table
        v-loading="loading"
        :data="loginLogList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="30" align="center" />
        <el-table-column
          label="日志编号"
          align="center"
          prop="id"
          v-if="true"
        />
        <el-table-column
          label="用户名"
          align="center"
          prop="userName"
          v-if="true"
        />
        <el-table-column label="手机号" align="center" prop="phoneNumber" />
        <el-table-column label="登录IP" align="center" prop="ipAddr" />
        <el-table-column label="登录地点" align="center" prop="loginLocation" />

        <el-table-column label="登录状态" prop="status">
          <template #default="{ row }">
            <el-tag
              :type="LoginLogStyleTypeMap.get(row.status ?? -1) ?? 'info'"
              >{{ row.statusMsg }}</el-tag
            >
          </template>
        </el-table-column>

        <el-table-column label="登录日期" align="center" prop="loginTime" />
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-button
              link
              type="primary"
              icon="View"
              @click="handleDetail(scope.row)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getLoginLogList"
      />
    </el-card>

    <!-- 角色详情弹出框 -->
    <el-dialog
      v-model="dialogStatus.isVisible"
      :title="dialogStatus.title"
      width="55%"
      center
      append-to-body
      :show-close="false"
      :close-on-click-modal="false"
    >
      <el-descriptions class="margin-top" :column="3" size="large" border>
        <el-descriptions-item width="120px">
          <template #label>
            <div class="cell-item">
              <el-icon>
                <user />
              </el-icon>
              登录用户
            </div>
          </template>
          {{ currentDialogData.userName }}
        </el-descriptions-item>

        <el-descriptions-item width="120px">
          <template #label>
            <div class="cell-item">
              <el-icon>
                <iphone />
              </el-icon>
              手机号
            </div>
          </template>
          {{ currentDialogData.phoneNumber }}
        </el-descriptions-item>

        <el-descriptions-item>
          <template #label>
            <div class="cell-item" style="width: 120px">
              <el-icon>
                <location />
              </el-icon>
              登录位置
            </div>
          </template>
          {{ currentDialogData.loginLocation }}
          {{ currentDialogData.ipAddr}}
        </el-descriptions-item>

        <el-descriptions-item width="120px">
          <template #label>
            <div class="cell-item">
              <icon-ic-baseline-computer/>
              浏览器
            </div>
          </template>
          <el-tag size="small">{{ currentDialogData.browser }}</el-tag>
        </el-descriptions-item>

        <el-descriptions-item width="120px">
          <template #label>
            <div class="cell-item">
              <icon-ic-baseline-computer/>
              操作系统
            </div>
          </template>
          <el-tag size="small">{{ currentDialogData.os }}ms</el-tag>
        </el-descriptions-item>

        <el-descriptions-item width="120px">
          <template #label>
            <div class="cell-item">
              <icon-ic-baseline-access-time/>
              登录时间
            </div>
          </template>
          {{ currentDialogData.loginTime }}
        </el-descriptions-item>
      </el-descriptions>

      <el-descriptions class="margin-top" :column="3" size="large" border>
        <el-descriptions-item width="135px">
          <template #label>
            <div class="cell-item">
              <el-icon>
                <flag />
              </el-icon>
              登录结果
            </div>
          </template>
          {{ currentDialogData.msg }}
        </el-descriptions-item>
      </el-descriptions>
      <el-button
        plain
        size="large"
        icon="Close"
        style="margin: 20px 10px 10px 700px"
        @click="handleCloseDialog"
      >
        关闭
      </el-button>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  getLoginLogList as getLoginLogListApi,
  getLoginLogDetail as getLoginLogDetailApi,
  deleteLoginLog as deleteLoginLogApi,
  cleanLoginLog as cleanLoginLogApi,
} from "@/service/api/system/loginLog";
import {
  User,
  Location,
  Iphone,
  Flag,
} from "@element-plus/icons-vue";
import { checkUser } from "@/service/api/system/user/types";
import { ElButton, ElForm } from "element-plus";
import RightToolbar from "@/components/RightToolbar/index.vue";
import Pagination from "@/components/Pagination/index.vue";
import { BasePageResponse, BaseResponse } from "@/service/api/type.ts";
import { SysLoginLogVo } from "@/service/api/system/loginLog/types.ts";
import { to } from "await-to-js";
import {
  LoginLogStatusMap,
  LoginLogStyleTypeMap,
} from "@/maps/system/loginLog/loginLogStatusMaps.ts";

// 列表数据
const loginLogList = ref<SysLoginLogVo[]>([]);

const loading = ref(true);
const ids = ref<Array<string>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const queryFormRef = ref(ElForm);
const showSearch = ref(true);

// 初始dialog状态
const initDialogStatus = {
  isVisible: false,
  title: "",
};

// 状态
const statusArr = reactive([
  {
    value: 0,
    label: "成功",
  },
  {
    value: 1,
    label: "失败",
  },
]);

// const operatorTypeArr = reactive([
//   {
//     value: 0,
//     label: "其他",
//   },
//   {
//     value: 1,
//     label: "后台用户",
//   },
//   {
//     value: 2,
//     label: "app端用户",
//   },
// ]);

// 初始角色详情dialogData数据
const initDialogData: SysLoginLogVo = {
  id : "",
  userName : "",
  phoneNumber : "",
  status : "",
  ipAddr : "",
  loginLocation : "",
  browser : "",
  os : "",
  msg : "",
  loginTime : undefined
};

// 初始query参数
const initQueryParams = {
  userName: "",
  phoneNumber: "",
  ipAddr: "",
  timeRange: [null, null],
  status: 0,
  pageNum: 1,
  pageSize: 10,
  orderByColumn: "loginTime",
  orderType: "desc",
};

// 搜索框数据
const data = reactive({
  queryParams: { ...initQueryParams },
  rules: {
    id: [{ required: true, message: "主键不能为空", trigger: "blur" }],
    name: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
    age: [{ required: true, message: "年龄不能为空", trigger: "blur" }],
    email: [{ required: true, message: "邮箱不能为空", trigger: "blur" }],
  },
  dialogStatus: { ...initDialogStatus },
  currentDialogData: {
    ...initDialogData,
  },
});
const { queryParams, currentDialogData, dialogStatus } = toRefs(data);

/**
 * 搜索按钮操作
 */
const handleQuery = () => {
  // console.log(queryParams.value)
  queryParams.value.pageNum = 1;
  getLoginLogList();
};

/**
 * 重置按钮操作
 */
const resetQuery = () => {
  queryFormRef.value.resetFields();
  handleQuery();
};

/**
 * 获取登录日志列表
 */
const getLoginLogList = async (): Promise<boolean> => {
  loading.value = true;

  console.log(queryParams.value);
  const [err, res] = await to<BasePageResponse<SysLoginLogVo>, any>(
    getLoginLogListApi(queryParams.value),
  );

  if (!err) {
    console.log("!!!", res);
    loginLogList.value = res?.rows ?? [];
    total.value = Number(res?.total ?? 0);
    loginLogList.value.forEach((item: SysLoginLogVo) => {
      item.statusMsg = LoginLogStatusMap.get(item.status ?? "") ?? "未知";
    });

    loading.value = false;
    return true;
  }
  loading.value = false;
  return false;
};

/**
 * 多选框选中数据
 */
const handleSelectionChange = (selection: checkUser[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
  console.log(ids.value);
};

/**
 * 查看详情按钮
 */
const handleDetail = async (row: any) => {
  dialogStatus.value.title = "登录日志详情";
  dialogStatus.value.isVisible = true;
  console.log(row.id);
  const { data } = await getLoginLogDetailApi(row.id);
  currentDialogData.value = data;
  console.log(data);
};

/**
 * 关闭dialog
 */
const handleCloseDialog = () => {
  dialogStatus.value = Object.assign({}, initDialogStatus);
};

/**
 * 处理删除按钮操作
 */
const handleDelete = async () => {
  // 询问是否删除
  const [err, confirm] = await to<string, string>(
    ElMessageBox.confirm("此操作将永久删除该登录日志, 是否继续?", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }),
  );

  if (err === "cancel") {
    ElMessage({
      message: "取消删除",
      type: "info",
    });
  } else if (confirm === "confirm") {
    const [err] = await to<BaseResponse<any>, any>(
      deleteLoginLogApi(ids.value),
    );

    if (!err) {
      ElMessage({
        message: "删除登录日志成功",
        type: "success",
      });
      await getLoginLogList();
    }
  }
};

/**
 * 清空所有日志
 */
const handleCleanAll = async () => {
  // 询问是否删除
  const [err, confirm] = await to<string, string>(
    ElMessageBox.confirm("是否确定清空所有登录日志？", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }),
  );

  if (err === "cancel") {
    ElMessage({
      message: "取消清空",
      type: "info",
    });
  } else if (confirm === "confirm") {
    const [err] = await to<BaseResponse<any>, any>(cleanLoginLogApi());

    if (!err) {
      ElMessage({
        message: "清空登录日志成功",
        type: "success",
      });
    }
  }
};

onMounted(() => {
  getLoginLogList();
});
</script>

<style scoped lang="scss">
.el-date-pickerv {
  width: 900px;
}

.dialogForm {
  padding: 0 0 45px;

  // background-color: pink;
  .el-input {
    width: 219px;
  }
}

.dialogFooter {
  margin: 55px 0 0 220px;
}

.innerDialogFooter {
  margin: 55px 0 0 230px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;

  .setting {
    margin-left: 30px;
  }
}

.innerFooter {
  margin: 20px 0 0 200px;
}
</style>
